#include <iostream>
#include <string>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

using namespace std;

int x = 100;
void show(const string &name)
{
    cout << name << ", pid: " << getpid() << " " << x << "\n"
         << endl;
}
// 验证线程概念
void *threadRun(void *args)
{
    const string name((char *)args);
    while (true)
    {
        show(name);
        sleep(1);
    }
}
int main()
{
    //注意：以下创建线程是有问题的
    // 创建一个线程
    // pthread_t tid;
    // pthread_create(&tid, nullptr, threadRun, (void *)"thread 1");

    // 创建一批线程
    pthread_t tid[5];
    char name[64];
    for (int i = 0; i < 5; i++)
    {
        // 格式化文本到指定缓冲区
        snprintf(name, sizeof(name), "%s-%d", "thread", i);
        pthread_create(tid + i, nullptr, threadRun, (void *)name);
        sleep(1);//缓解传参bug
    }
    // 主线程要做的事
    while (true)
    {
        cout << "main thread,pid: " << getpid() << endl;
        sleep(3);
    }
    return 0;
}
